<template>
  <div class="app-container" style="margin-left: 20px">
    <el-form
      ref="taskform"
      :model="sizeForms"
      :rules="formrules"
      label-width="100px"
    >
      <el-form-item label="任务名称" prop="task_name">
        <el-input
          v-model="sizeForms.task_name"
          class="adds"
          placeholder="请输入任务名称"
        />
      </el-form-item>
      <el-form-item label="cron" prop="cron">
        <el-input
          v-model="sizeForms.cron"
          class="adds"
          placeholder="请输入cron内容"
        />
      </el-form-item>
      <el-form-item label="cron说明:">
        格式为：* * * * * cd /data/logs/cron/ &&  /usr/bin/python xxx.py >> /data/logs/cron/xxx.log 2>&1；  *****代表：分、小时、日、月、星期； xxx.py：为脚本名称；
      </el-form-item>
      <el-row>
        <el-col :span="5">
          <el-form-item>
            <el-upload
              ref="uploadfile"
              v-model="sizeForms.uploadfile"
              class="uploadfile"
              accept=".py"
              :file-list="uploadfile"
              :on-change="handleChange"
              action="#"
              :show-file-list="true"
              :auto-upload="false"
              :limit="1"
            >
              <el-button slot="trigger" type="primary">选取文件</el-button>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item>
            <el-button
              type="primary"
              @click="dialogFormAdd('taskform')"
            >添加任务</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :header-cell-style="{ background: 'dodgerblue', color: '#eeeeee' }"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @sort-change="sortChange"
    >
      <el-table-column label="序号" width="70px" align="center">
        <template slot-scope="scope">{{ scope.$index + 1 }}</template>
      </el-table-column>
      <el-table-column
        v-if="idhidden"
        label="ID"
        prop="id"
        align="center"
        width="80"
      >
        <template slot-scope="{ row }">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="任务名称" width="200px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.task_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="执行时机" width="850px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.begin_time }}</span>
        </template>
      </el-table-column>
      <el-table-column label="添加时间" width="150px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.add_time | parseTime("{y}-{m}-{d} {h}:{i}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="400px"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button
            size="mini"
            type="success"
            @click="tableRowRun(row.id)"
          >
            执行
          </el-button>
          <el-button size="mini" type="primary" icon="el-icon-edit" @click="tableRow(row)" />
          <el-button
            v-if="row.type === 0"
            size="mini"
            type="primary"
            @click="tableRowRunStop(1, row.id)"
          >
            启动
          </el-button>
          <el-button
            v-if="row.type === 1"
            size="mini"
            type="danger"
            @click="tableRowRunStop(0, row.id)"
          >
            停止
          </el-button>
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="tableRowDelTask(row.type, row.id)"
          />
          <el-button type="primary" size="mini" @click="tableRowTaskLog(row)">
            日志
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page_num"
      :limit.sync="listQuery.page_per"
      @pagination="getList"
    />
    <mini
      v-if="dialogAdd.show"
      ref="popBox"
      :size-forms="sizeForms"
      destroy-on-close="true"
      @closePop="closePop"
      @changeLogList="changeLogList"
    />
    <editTask
      v-if="dialogedit.show"
      ref="popBox"
      :size-forms="sizeFormsedit"
      destroy-on-close="true"
      @closePop="closePop"
    />
  </div>
</template>
<script>
import { Message } from 'element-ui'
import mini from './components/edit'
import {
  selTask,
  selTasklog,
  task_upload,
  insertTask,
  delTask,
  runStop,
  taskRun
} from '@/api/task'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import editTask from './components/edit_task'

export default {
  name: 'ComplexTable',
  components: {
    Pagination,
    mini,
    editTask
  },
  data() {
    return {
      dialogAdd: {
        show: false
      },
      dialogedit: {
        show: false
      },
      tableKey: 0,
      list: null,
      total: 0,
      edit: false,
      idhidden: false,
      listLoading: true,
      listQuery: {
        id: '',
        page_num: 1,
        page_per: 10
      },
      sizeForms: {},
      sizeFormsedit: {},
      logListQuery: {
        id: '',
        page_num: 1,
        page_per: 10
      },
      task_name: '',
      cron: '',
      uploadfile: [],
      user_id: '',
      formrules: {
        task_name: [
          { required: true, message: '任务名称不能为空', trigger: 'blur' }
        ],
        cron: [{ required: true, message: 'cron不能为空', trigger: 'blur' }],
        uploadfile: [
          { required: true, message: '脚本文件不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
    // this.getGroupN()
  },
  methods: {
    // 通过onchanne触发方法获得文件列表
    handleChange(file, fileList) {
      this.uploadfile = fileList
    },
    dialogFormAdd(taskform) {
      this.$refs[taskform].validate((valid) => {
        if (valid) {
          // this.uploadfile();
          const formData = new FormData()
          if (this.uploadfile.length === 0) {
            Message.error('请上传脚本文件!')
          } else {
            formData.append('file', this.uploadfile[0].raw)
            formData.append('user_id', this.$store.state.user.token)
            task_upload(formData).then((res) => {
              if (res.code === 20000) {
                this.dialogFormAddTask()
              } else {
                Message.error(res.message)
              }
            })
          }
        }
      })
    },
    dialogFormAddTask() {
      insertTask({
        task_name: this.sizeForms.task_name,
        cron: this.sizeForms.cron,
        user_id: this.$store.state.user.token
      }).then((res) => {
        if (res.code === 20000) {
          Message.success(res.message)
        } else {
          Message.error(res.message)
        }
      })
      this.getList()
    },
    // getHeader() {
    //   var req = new XMLHttpRequest();
    //   req.open("GET", document.location, false);
    //   req.send(null);
    //   console.log(req.getAllResponseHeaders());
    // },
    closePop(formName) {
      this.dialogAdd.show = false
      this.dialogedit.show = false
    },
    getList() {
      this.listLoading = true
      selTask(this.listQuery).then((response) => {
        this.list = response.data.items
        this.total = response.data.total
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 0.5 * 1000)
      })
    },
    handleFilter(groudId) {
      this.listQuery.page_num = 1
      this.listQuery.page_per = 10
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    // addCase() {
    //   this.dialogAdd.show = true;
    //   this.edit = false;
    //   this.sizeForms.gns = this.group_namelist;
    // },
    tableRowTaskLog(row) {
      // this.edit = true;
      this.logListQuery.id = row.id
      selTasklog(this.logListQuery).then((response) => {
        const items = response.data.items
        if (items.length === 0) {
          Message.success(row.task_name + '暂时没有任何操作记录')
        } else {
          this.sizeForms = response.data
          this.dialogAdd.show = true
          // console.log(this.logListQuery)
        }
      })
    },
    // 切换日志页
    changeLogList(e) {
      if (e) {
        this.logListQuery.page_num = e.page
        this.logListQuery.page_per = e.limit
        // console.log(this.logListQuery)
        selTasklog(this.logListQuery).then((response) => {
          const items = response.data.items
          // console.log(items)
          if (items.length !== 0) {
            this.sizeForms = response.data
          }
        })
      }
    },
    tableRow(row) {
      this.sizeFormsedit = row
      this.dialogedit.show = true
    },
    tableRowRunStop(status, id) {
      runStop({
        status: status,
        task_id: id,
        // user_id
        user_id: this.$store.state.user.token
      }).then((res) => {
        if (res.code === 20000) {
          this.getList()
          Message.success(res.message)
        } else {
          Message.error(res.message)
        }
      })
    },
    tableRowRun(id) {
      taskRun({
        task_id: id,
        user_id: this.$store.state.user.token
      }).then((res) => {
        if (res.code === 20000) {
          this.getList()
          Message.success(res.message)
        } else {
          Message.error(res.message)
        }
      })
    },
    tableRowDelTask(type, id) {
      if (type === 1) {
        Message.error('请先停止执行任务再删除！')
      } else {
        delTask({
          task_id: id,
          // user_id
          user_id: this.$store.state.user.token
        }).then((res) => {
          if (res.code === 20000) {
            this.getList()
            Message.success(res.message)
          } else {
            Message.error(res.message)
          }
        })
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    }
  }
}
</script>
